package com.dongrj.framework.starter.log.filter;

import com.dongrj.framework.core.utils.StringUtils;
import com.dongrj.framework.starter.log.utils.TraceIdUtils;

import javax.servlet.*;
import javax.servlet.http.HttpServletRequest;
import java.io.IOException;

/**
 * @author dongrongjun
 * @date 2020/08/04
 */
public class LogMDCServletFilter implements Filter {


    @Override
    public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
        insertIntoMDC(request);
        try {
            chain.doFilter(request, response);
        } finally {
            clearMDC();
        }
    }

    private void insertIntoMDC(ServletRequest servletRequest) {
        if (servletRequest instanceof HttpServletRequest) {
            HttpServletRequest request = (HttpServletRequest) servletRequest;
            TraceIdUtils.setTraceId(request, StringUtils::randomUUID);
        }
    }

    private void clearMDC() {
        TraceIdUtils.removeTraceId();
    }

    @Override
    public void destroy() {

    }

    @Override
    public void init(FilterConfig arg0) {

    }

}
